package Odinote::DocTabs;

use strict;
use warnings;

use Glib qw/TRUE FALSE/;
use Gtk2;
use Gtk2::Pango;
use Gtk2::SourceView;
use Encode;

my $self;
my @tabs;
my $lasttab = 0;
my $langmanager;
my $latexlang;

sub _init
{
  shift;
  $self = shift;
  my $source = shift;

  $langmanager = Gtk2::SourceView::LanguagesManager->new;
  $latexlang = $langmanager->get_language_from_mime_type("text/x-tex");

  if($source)
  {
    add_document($source);
  }
  else
  {
    add_document();
  }
}

sub add_document
{
  shift;
  my $source = shift;
  $lasttab++;
  $tabs[$lasttab] = Gtk2::ScrolledWindow->new(undef, undef);
  $tabs[$lasttab]->set_name('scrolledwindow_tab'.$lasttab);
  $tabs[$lasttab]->set_policy('automatic','automatic');
  my $txtview = Gtk2::SourceView::View->new;
  $txtview->set_name('textview_tab'.$lasttab);
  my $tablabel = Gtk2::Label->new;
  $tablabel->set_name('label_tab'.$lasttab);
  $tablabel->set_selectable(FALSE);
  $tablabel->set_ellipsize('end');
  $tablabel->set_width_chars(15);
  $tablabel->set_max_width_chars(15);
  $txtview->set_wrap_mode('word-char');
  if($latexlang)
  {
    $txtview->get_buffer->set_language($latexlang);
    $txtview->get_buffer->set_highlight(1);
  }
  else
  {
    $txtview->get_buffer->set_highlight(0);
  }
  if($source)
  {
    open(NF, $source) or print "Could not open file ".$source;
    my @lines = <NF>;
    close(NF);

    foreach my $line (@lines)
    {
      $line = encode('UTF-8', $line);
      $txtview->get_buffer->insert($txtview->get_buffer->get_end_iter, $line);
    }
    $tablabel->set_text("Opened Document ".$lasttab);
  }
  else
  {
    $tablabel->set_text("New Document ".$lasttab);
    foreach my $lang ($langmanager->get_available_languages)
    {
      $txtview->get_buffer->insert($txtview->get_buffer->get_end_iter, $lang->get_name."\n");
      foreach my $mt ($lang->get_mime_types)
      {
        $txtview->get_buffer->insert($txtview->get_buffer->get_end_iter, "\t".$mt."\n");
      }
    }
  }
  $tabs[$lasttab]->add($txtview);
  $tabs[$lasttab]->show_all;
  my $npind = $self->append_page($tabs[$lasttab], $tablabel);
  $self->set_current_page($npind);
}

sub close_current
{
  $self->remove_page($self->get_current_page);
}

sub copy_selected
{

}

sub cut_selected
{
  print "Cutting Text.\n";
  $self->get_nth_page($self->get_current_page)->get_child->get_buffer->cut_clipboard(Gtk2::Clipboard->new);
}

sub paste_selected
{

}

1;
